/*
 * Creator:     DYK
 * CreatDate:   2021-12-17
 * descripts：  录入诊断目录信息（新病种维护）
 * */
import React from 'react';
import moment from 'moment';
import { Form, Row, Col, Input, Table, Select, Tree, Button, Modal, message, Divider, DatePicker, Icon, Card, Checkbox, Radio, Badge, Fragment, Pagination, Popconfirm } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';
import './css/OrderTemple.less';
import './css/ApplicationSetting.less';
import NewDiagnosticClassificDeatil from './NewDiagnosticClassificDeatil';

const { Search } = Input;

const formItemLayout = { // label 和input宽度
  labelCol: { span: 9 },
  wrapperCol: { span: 12 }
};

const formItemLayoutR = {
  labelCol: { span: 9 },
  wrapperCol: { span: 15 }
};
const FormItem = Form.Item;
const Option = Select.Option;
const NewDiagnosticClassificationMain = Form.create()(
  class NewDiagnosticClassificationMain extends React.Component {
    cacheOriginData = {};
    constructor(props) {
      super(props);
      this.state = {
        expandedKeys: [],
        selectedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        threeData: [],
        record: {},
        baseParentType: [],
        inputValue: "",
        checked: true,//默认选择生效
        visible: false,//添加/修改分类设置弹窗显示
        isMod: -1,//是否点击编辑
        tipStatus: false,
        canAdd: false,
        baseParms:{},   // 医院下拉参数对象
        hospId:undefined  //选择当前的医院ID
      }
    }

    componentDidMount = () => {
      this.handleQuery();
      this.getBaseParams(); //查询医院基础信息
    };

    generateList = data => {
      let dataList = [];
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const { key } = node;
        dataList.push({ key, title: key });
        this.setState({
          dataList,
        });
        if (node.children) {
          this.generateList(node.children);
        }
      }
    };

    //获取左侧搜索输入框值
    changeInfo = (e) => {
      this.setState({
        searchCategoryName: e.target.value
      })
    };
    //回车查找分类设置数据
    handleQuery = () => {
      let data = {};
      data = {
        params: [{
          hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
          upDirectID: "",
          locID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : "",
          inputValue: this.state.inputValue && this.state.inputValue || ""
        }],
      };
      $http.post('urlS', this, {
        // code: '03050253',
        code: 'pr350253',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              threeData: res.result.data,
            });
            if (res.result.data.length == 0) {
              this.setState({
                tipStatus: true
              })
            } else {
              this.setState({
                tipStatus: false
              })
            }
          } else {

          }
        }
      })
    };

    //获取对应的医院基础信息数据
    getBaseParams = () => {
      let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
      let code = '03030026';
      let data = {
        "params": [{}
        ],
        "code": code,
        "session": [{
          "userID": sessionInfo.userID,
          "locID": sessionInfo.locID,
          "groupID": sessionInfo.groupID,
          "hospID": sessionInfo.hospID,
          "sessionID": sessionInfo.sessionID,
          "hospCode": sessionInfo.hospCode,
          "language": sessionInfo.language,
          "hostName": sessionInfo.hospDesc,
          "ipv4": "",
          "ipv6": "",
          "mac": ""
        }
        ]
      };
      $http.post("urlS", this, {
        code: code,
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              baseParms: { ...this.state.baseParms, ...{ hosp: res.result.Data } }
            })
          } else {
            message.error('失败：' + res.errorMessage);
          }
        },
        error: function (error) {
          message.error('失败：' + error);
        }
      });
    };


    //同步病种及关联信息
    syncHospInfo = () => {
      let {hospId} = this.state;
      let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
      let code = 'pr350250';

      let data = {
        "params": [{
          "syncHospId": +hospId
        }],
        "code": code,
        "session": [{
          "userID": sessionInfo.userID,
          "locID": sessionInfo.locID,
          "groupID": sessionInfo.groupID,
          "hospID": sessionInfo.hospID,
          "sessionID": sessionInfo.sessionID,
          "hospCode": sessionInfo.hospCode,
          "language": sessionInfo.language,
          "hostName": sessionInfo.hospDesc,
          "ipv4": "",
          "ipv6": "",
          "mac": ""
        }
        ]
      };
      // console.log('同步操作入参',data);
      $http.post("urlS", this, {
        code: code,
        data: data,
        success: function (res) {
          // console.log('同步操作反参',res);
          if (+res.errorCode === 0) {
             message.success('同步数据成功！');
          } else {
            message.error('失败：' + res.errorMessage);
          }
        },
        error: function (error) {
          message.error('失败：' + error);
        }
      });
    };

    //绑定医院id
    onChangeHospName = (value) => {
      this.setState({
        hospId: value
      });
    };

    //调子组件
    onAttRef = (ref) => {
      this.childAtt = ref
    };
    //添加分类设置弹出
    openDocMes = () => {
      this.props.form.resetFields();
      // console.log("this.state.selectedKeys[0]", this.state.selectedKeys[0])
      this.setState({
        isMod: -1,
        visible: true
      }, () => {
        this.getParentSelect((this.state.selectedKeys && this.state.selectedKeys[0]) || "")
      })
    };
    //点击添加/修改分类设置弹窗确认按钮
    handleOk = (e) => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          let data = {};
          data = {
            params: [{
              ID: this.state.isMod == 1 ? (this.state.selectedKeys && this.state.selectedKeys[0]) : "",
              upDirectID: this.state.isMod == 1 ? this.state.upDirectID : values.upDirectID,
              userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
              locID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : "",
              hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
              directENDesc: values.directENDesc,
              directDesc: values.directDesc,
              startDate: values.dateFrom ? moment(values.dateFrom).format('YYYY-MM-DD') : undefined,//生效日期
              stopDate: values.dateTo ? moment(values.dateTo).format('YYYY-MM-DD') : undefined,//失效日期
            }],
          }
          $http.post('urlS', this, {
            code: '03050254',
            data: data,
            success: function (res) {
              if (+res.errorCode === 0) {
                if (this.state.isMod == 1) {
                  message.success("修改成功");
                  this.initData()
                } else {
                  message.success("新建成功");
                  this.initData();
                  this.setState({
                    inputValue: ""
                  })
                }
                this.setState({
                  visible: false,
                });
                this.handleQuery()

              } else {

              }
            }
          })
        }
      })
    };
    //获取上级分类下拉框
    getParentSelect = (directID) => {
      let data = {};
      data = {
        params: [{
          directID: directID ? directID : "",
          hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
        }],
      };
      $http.post('urlS', this, {
        // code: '03050259',
        code: 'pr350259',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              baseParentType: res.result,
            })
          }
        }
      })
    };
    //编辑分类
    handleEdit = (e, item, flag) => {
      if (e && e.stopPropagation) {
        e.stopPropagation();
      }
      // console.log(e)
      //编辑
      if (flag == 1) {
        this.getParentSelect(item.ID);
        this.props.form.resetFields();
        this.setState({
          record: item,
          isMod: 1,
          visible: true
        }, () => {
          this.props.form.setFieldsValue({
            directDesc: item.directDesc,
            directENDesc: item.directENDesc,
            upDirectID: item.upDirectID,
            dateFrom: item.startDate ? moment(item.startDate, "YYYY-MM-DD") : moment(),
            dateTo: item.stopDate ? moment(item.stopDate, "YYYY-MM-DD") : undefined,
          });
        })
      } else {
        //删除
        let datas = {};
        datas = {
          params: [{
            userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
            ID: item.ID,
          }],
        };
        $http.post('urlS', this, {
          code: '03050255',
          data: datas,
          success: function (res) {
            if (+res.errorCode === 0) {
              message.success("删除成功");
              this.handleAllClear()
            }
          }
        })
      }
    };
    getRightDeatil = (HBid) => {
      let data = {};
      data = {
        params: [{
          searchCode: "",
          HBid: HBid,
        }],
      };
      $http.post('urlS', this, {
        code: '03010010',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.data) {
            this.setState({
              rightData: res.data
            })

          }
        }
      })
    };
    //初始化信息
    initData = () => {
      this.setState({
        isMod: -1,
        ordShow: false,
        tempChildDis: false
      })

    };
    //点击添加/修改分类设置弹窗取消按钮
    handleCancel = () => {
      this.setState({
        visible: false,
        record: {}
      });
      this.initData()
    };
    findApp = () => {
      this.handleQuery()
    };
    //判断某个字符出现几次 aStr为某字符串 aChar为某字符
    getStrCount = (aStr, aChar) => {
      var regex = new RegExp(aChar, 'g'); // 使用g表示整个字符串都要匹配
      var result = aStr.match(regex);
      var count = !result ? 0 : result.length;
      return count;
    };
    //展开目录
    onExpand = expandedKeys => {
      this.setState({
        expandedKeys,
        autoExpandParent: false,
      });
    };
    //选中目录
    handleSelect = (selectedKeys, e) => {
      // console.log("selectedKeys---选中",selectedKeys,"getStrCount",this.getStrCount(e.node.props.selectKey,"-"),"e.node.props.selectKey",e.node.props.selectKey)
      this.setState({
        selectedKeys,
        upDirectID: e.node.props.upDirectID,
        title: e.node.props.title,
        upDirectDesc: e.node.props.upDirectDesc,
        autoExpandParent: false,
      }, () => {
        //取消选中
        if (selectedKeys && selectedKeys[0] == undefined) {
          this.childAtt.clearInfo("2");
          this.childAtt.getInfo({}, "");
          this.setState({
            canAdd: false
          })
        } else {
          //限制添加2层 选中时
          if (this.getStrCount(e.node.props.selectKey, "-") == 2) {
            this.setState({
              canAdd: true
            })
          } else {
            this.setState({
              canAdd: false
            })
          }
          this.handleInfo(this.state.selectedKeys && this.state.selectedKeys[0])
        }
      });
    };
    handleInfo = (directID) => {
      let data = {};
      data = {
        params: [{
          directID: directID && directID || "",
        }],
      };
      $http.post('urlS', this, {
        // code: '03050256',
        code: 'pr350256',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result.data) {
            this.childAtt.getInfo({}, directID && directID || "", res.result.data)
          }
        }
      })
    };

    //搜索 框 值
    handleInt = (e) => {
      if (e) {
        this.setState({
          inputValue: e.target.value
        })
      } else {
        this.setState({
          inputValue: ""
        })
      }
    };
    //回车搜索 清除
    handleSearch = () => {
      this.setState({
        selectedKeys: [],
        autoExpandParent: true,
        threeData: [],
        tipStatus: true
      }, () => {
        this.handleRest()
      })

    };
    handleRest = () => {
      this.childAtt.clearInfo("2");
      this.childAtt.getInfo({}, "");
      this.handleQuery()
    };
    //状态清空
    handleAllClear = () => {
      this.setState({
        title: "",
        selectedKeys: [],
        threeData: [],
        tipStatus: true
      }, () => {
        this.handleRest()
      })

    };
    newAdd = () => {
      this.setState({
        rowIds: "",
      });
      this.childAtt.clearInfo()
    };
    render() {
      // 医院下拉选项
      let {baseParms} = this.state;

      const { getFieldDecorator } = this.props.form;
      const { searchValue, expandedKeys, autoExpandParent, baseParentType, threeData, record, } = this.state;
      // gData = threeData
      const loop = data =>
        data.map(item => {
          const index = item.title.indexOf(searchValue);
          const beforeStr = item.title.substr(0, index);
          const afterStr = item.title.substr(index + searchValue.length);
          const title =
            index > -1 ? (
              <span>
                {beforeStr}
                <span className="site-tree-search-value">{searchValue}</span>
                {afterStr}
              </span>
            ) : (
              <p>
                <span>{item.title}</span>
              </p>
            );
          if (item.children) {
            // return (
            //   <TreeNode key={item.key} title={title}>
            //     {loop(item.children)}
            //   </TreeNode>
            // );
            return {
              title,
              key: item.ID,
              upDirectID: item.upDirectID,
              selectKey: item.key,
              upDirectDesc: item.upDirectDesc,
              children: loop(item.children),
            };
          }
          // return <TreeNode key={item.key} title={title} />;
          return {
            title,
            key: item.ID,
            upDirectID: item.upDirectID,
            selectKey: item.key,
            upDirectDesc: item.upDirectDesc,
          };
        });
      let parentType = [];
      baseParentType && baseParentType.map(item => {
        parentType.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
      });
      return (
        <div>
          <Row gutter={60} className="applicationDom diagDom" style={{ marginRight: "0" }}>

            {/*诊断分类--左侧模块*/}
            <Col span={6} style={{ paddingRight: "0" }}>
              <Card title="诊断分类" bordered={false} style={{ marginRight: "4px", }}>
                <Row>
                {/*下拉同步医院数据*/}
                  <Col span={18}>
                    <Select
                        showSearch
                        allowClear
                        optionFilterProp="label"
                        style={{ width: '260px' }}
                        placeholder="请选择需要同步的医院"
                        value={this.state.hospId}
                        onChange={this.onChangeHospName}
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                      {
                        baseParms.hosp && baseParms.hosp.map(function (item, index) {
                          return <Option key={item.id}  title={item.descripts} value={item.id}>{item.descripts}</Option>
                        })
                      }
                    </Select>
                  </Col>

                  <Col span={6}>
                    <Button type="primary" onClick={this.syncHospInfo}>同步</Button>
                  </Col>
                </Row>

                {
                  this.state.tipStatus ?
                    <Row style={{ textAlign: "center" }}>
                      暂无数据
                    </Row> : <Tree
                      onExpand={this.onExpand}
                      expandedKeys={expandedKeys}
                      autoExpandParent={autoExpandParent}
                      onSelect={this.handleSelect}
                      treeData={loop(this.state.threeData)}
                    />
                }

                {/*添加诊断分类*/}
                <div className="ordTempDateil">
                  <Modal
                    key='2'
                    width='416px'
                    visible={this.state.visible}
                    title={this.state.isMod == 1 ? "编辑分类" : "添加分类"}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    footer={[
                      <Button key="submitc" type="primary" onClick={this.handleCancel}>取消</Button>,
                      <Button key="submits" type="primary" onClick={this.handleOk}>确定</Button>,
                    ]}>
                    <div>
                      <Form>
                        <Row gutter={60}>
                          <Col span={24}>
                            <FormItem label='目录描述' {...formItemLayout}>
                              {getFieldDecorator('directDesc', {
                                initialValue: record && record.directDesc || undefined,
                                rules: [{ required: true, message: '请输入描述' }],
                              })(
                                <Input placeholder="不能超过10个字" maxLength={10} style={{ width: "100%" }} />
                              )}
                            </FormItem>
                          </Col>
                        </Row>
                        <Row gutter={60}>
                          <Col span={24}>
                            <FormItem label='描述英文'  {...formItemLayout}>
                              {getFieldDecorator('directENDesc', {
                                initialValue: record && record.directENDesc || undefined,
                                rules: [{ required: false, message: '' }],
                              })(
                                <Input />
                              )}
                            </FormItem>
                          </Col>
                        </Row>
                        <Row gutter={60}>
                          <Col span={24}>
                            <FormItem label='上级分类'  {...formItemLayout}>
                              {getFieldDecorator('upDirectID', {
                                initialValue: undefined,
                                rules: [{ required: this.state.isMod == 1 || (this.state.selectedKeys && this.state.selectedKeys[0] == undefined) ? false : true, message: '请选择上级分类' }],
                              })(
                                <Select style={{ width: "100%" }} disabled={this.state.isMod == 1 || (this.state.selectedKeys && this.state.selectedKeys[0] == undefined)}>
                                  {parentType}
                                </Select>
                              )}
                            </FormItem>
                          </Col>
                        </Row>
                        <Row gutter={60}>
                          <Col span={24} >
                            <FormItem label='生效日期' {...formItemLayout}>
                              {getFieldDecorator('dateFrom', {
                                initialValue: record.startDate ? moment(record.startDate, "YYYY-MM-DD") : moment(),
                                rules: [{ required: true, message: '请选择生效日期' }],
                              })(
                                <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                  return curDate && curDate > moment().endOf('day');
                                }} />
                              )}
                            </FormItem>
                          </Col>
                        </Row>
                        <Row gutter={60}>
                          <Col span={24} >
                            <FormItem label='失效日期' {...formItemLayout}>
                              {getFieldDecorator('dateTo', {
                                initialValue: record.stopDate ? moment(record.stopDate, "YYYY-MM-DD") : undefined,
                                rules: [{ required: false, message: '' }],
                              })(
                                <DatePicker style={{ width: '100%' }} />
                              )}
                            </FormItem>
                          </Col>
                        </Row>
                        <Row>
                        </Row>
                      </Form>
                    </div>
                  </Modal>
                </div>

              </Card>
            </Col>

            {/*诊断录入信息--右侧模块*/}
            <Col span={18} className="right-dom" style={{ paddingLeft: "6px", paddingRight: "0" }}>
              <Card title={this.state.title && this.state.title ? this.state.title : "请选择左侧目录"} bordered={false} className="moreInfoCard" style={{ paddingRight: "0" }}>
                <p className="titleDom"> 录入诊断信息</p>
                <div>
                  <NewDiagnosticClassificDeatil localeProvider={this.state.localeProvider} newAdd={this.newAdd} handleInfo={this.handleInfo} onAttRef={this.onAttRef} handleQuery={this.handleQuery}></NewDiagnosticClassificDeatil>
                </div>
              </Card>
            </Col>
          </Row>
        </div>
      )
    }
  });
export default NewDiagnosticClassificationMain
